#include "user_login.h"

bool my_sand(char *buf, char *number)
{
    struct device *p = head; // 遍历链表
    while (p != NULL)
    {
        if (strstr(p->device_name, number)) // 找到设备
        {
            printf("找到%s设备%d,开始转发\n", p->device_name, p->socket);
            // 发送数据
            int size = write(p->socket, buf, strlen(buf));
            printf("发送的数据 %s :", buf);
            printf("发送的数据大小 %d\n", size);
            break;
        }

        p =p->next;
    }
}

bool USER_LGOIN(char *buf)
{
    char user[128] = {0}; // 分析字符串
    char password[128] = {0};
    char number[128] = {0};
    LOGIN_str(buf, user, password, number);
    FILE *fp = fopen("./Data/user_information.txt", "r+");
    if (fp == NULL)
    {
        printf("打开文件失败\n");
        return false;
    }
    while (1) // 遍历数据文件，比对账号和密码
    {
        char arr[128] = {0};
        char buf_user[128] = {0};
        char buf_password[128] = {0};
        char *set = fgets(arr, sizeof(arr), fp);
        if (set == NULL)
        {
            break;
        }
        LOGIN_str1(arr, buf_user, buf_password);
        buf_password[strlen(buf_password) - 1] = '\0'; // 去掉换行符
        int cmp1 = strcmp(user, buf_user); // 比较
        int cmp2 = strcmp(password, buf_password);
        if (set != 0 && cmp1 == 0 && cmp2 == 0) // 文件中有你输入的账号和密码（登入成功）
        {
            printf("账号密码正确%s\n",number);
            my_sand("ok", number);
            printf("登录成功\n");
            break;
        }
    }
    return true;
}

bool LOGIN_str(char *buf, char *user, char *password, char *number)
{
    char *p = strtok(buf, ",");
    int i = 0;
    while (p != NULL)
    {
        printf("p1 = %s\n", p);
        if (i == 0);

        else if (i == 1)
            strcpy(number, p);
        else if (i == 2)
            strcpy(user, p);
        else if (i == 3)
            strcpy(password, p);
        i++;
        p = strtok(NULL, ",");
    }
    return true;
}

bool LOGIN_str1(char *buf, char *user, char *password)
{
    char *p = strtok(buf, ",");
    int i = 0;
    while (p != NULL)
    {
        printf("p1 = %s\n", p);
        if (i == 0)
            strcpy(user, p);
        else if (i == 1)
            strcpy(password, p);
        i++;
        p = strtok(NULL, ",");
    }
    return true;
}
